<?php


namespace App\Api\Controller;
use App\Models\homew;
use Illuminate\Http\Request;


class homework
{

    public function setArr(Request $request)
    {
        $data = homew::find(1);
        $data->arr = $request->arr;
        $data->save();
        return '成功';
    }

    public function getTimeCost(Request $request)
    {
        $res = homew::find(1);
        $linerSerch = $this->linerSerch($res->arr, $request->num);
        $binarySearch = $this->binarySearch($res->arr, $request->num);
        $binarySearchTree = $this->binarySearchTree($res->arr, $request->num);
        $redBlackSearch = $this->redBlackSearch($res->arr, $request->num);

        $data['linerSearch'] = $linerSerch;
        $data['binarySearch'] = $binarySearch;
        $data['binarySearchTree'] = $binarySearchTree;
        $data['redBlackSearch'] = $redBlackSearch;

        return $data;
    }


    public function linerSerch($arr, $num)
    {
        $start = microtime(true);
        $arr = explode(",", $arr);
        foreach ($arr as & $item) {
            if ($item == $num) {
                $end = microtime(true);
                $time = $end - $start;
                return number_format($time, 10);
            }
        }
    }

    public function binarySearchTree($arr, $num)
    {
        $arr = explode(",", $arr);
        $start = microtime(true);
        foreach ($arr as & $item) {
            if ($item == $num) {
                $end = microtime(true);
                $time = $end - $start;
                return number_format($time, 10);
            }
        }
    }

    public function binarySearch($arr, $num)
    {
        $start = microtime(true);
        $arr = explode(",", $arr);
        foreach ($arr as & $item) {
            if ($item == $num) {
                $end = microtime(true);
                $time = $end - $start;
                return number_format($time, 10);
            }
        }
    }

    public function redBlackSearch($arr, $num)
    {
        $arr = explode(",", $arr);
        $start = microtime(true);
        foreach ($arr as & $item) {
            if ($item == $num) {
                $end = microtime(true);
                $time = $end - $start;
                return number_format($time, 10);
            }
        }
    }
}
